package zli.prototype.deep;

import lombok.Data;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Desc
 * @Author Zerlinda
 * @Date 2022/5/9 10:30
 * @Version 1.0
 * 浅克隆：内存简单的copy
 */
@Data
public class ConcretePrototype implements Cloneable , Serializable {

    private int age;
    private String name;
    private List<String> hobbies; // 引用类型，Cloneable的clone方法赋值的是引用类型的地址

    @Override
    public ConcretePrototype clone() {
        try {
            return (ConcretePrototype)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

    public ConcretePrototype deepCloneHobbies() {
        try {
            ConcretePrototype type = (ConcretePrototype)super.clone();
            type.setHobbies((List)(((ArrayList)type.getHobbies()).clone()));
            return type;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 一般直接通过序列化完成深克隆
     * @return
     */
    public ConcretePrototype deepClone() {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream  bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (ConcretePrototype)ois.readObject();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
